import { message } from "ant-design-vue";
import _ from "lodash-es";
import md5 from "md5";
// 表单序列化
export const serialize = (data: any): string => {
  const list: string[] = [];
  Object.keys(data).forEach((ele) => {
    list.push(`${ele}=${data[ele]}`);
  });
  return list.join("&");
};

export const formatZero = (num: number, len = 2) => {
  const str = `${num}`;
  if (str.length < len) {
    return (new Array(len).join("0") + str).substring(str.length - 1);
  }
  return str;
};
/**
 * 深拷贝
 * @param obj
 */
export const deepClone = (obj: any) => _.cloneDeep(obj);

/**
 * 加密字符串不可逆
 * @param str 加密对象
 */
export const encryptStr = (str: any) => md5(str);

/**
 * 对象加密部分字段
 * @param obj
 */
export const encryptStrByObj = (obj: any, list: string[]) => {
  const newObj = deepClone(obj);
  list.forEach((m) => {
    const str = newObj[m];
    if (str.constructor === String) {
      newObj[m] = encryptStr(str);
    }
  });
  return newObj;
};
/**
 * 将对象加密为字符串
 * @param obj 加密对象
 */
export const objEncodeToStr = (obj: any) => btoa(JSON.stringify(obj));
/**
 * 将字符串解密为对象
 * @param base64Str 加密后字符串
 */
export const strDecodeToObj = (str: string) => JSON.parse(atob(str));

// 合并对象
export function mergeByFirst<T>(distObject: T, srcObject: Partial<T>) {
  const distPropList = _.keys(distObject);
  const srcPropList = _.keys(_.omitBy(srcObject, _.isNil));
  const propList = _.intersection(distPropList, srcPropList);
  return {
    ...distObject,
    ..._.pick(srcObject, propList),
  };
}

export const showErr = (err: any) => {
  if (err.constructor === Error) {
    message.error("出错啦");
  } else if (err.errorFields) {
    message.warning(err.errorFields[0].errors[0]);
  } else {
    message.warning("出错啦");
  }
};
